package cn.edu.ccut.refactor;

import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.ui.actions.SelectionDispatchAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.PlatformUI;


/**
 * 
 * @author Bai Yucheng 2008-4-16
 * 
 */
public class RenameSaturnModuleAction extends SelectionDispatchAction {
	private ISelection selection;

	public RenameSaturnModuleAction(IWorkbenchSite site) {
		super(site);
		setText(Messages.getString("RenameSaturnModuleAction.0"));  //$NON-NLS-1$
		this.selection = getSelection();
	}

	@Override
	public void run() {
		if (!RefactorUtil.saveAll())
			return;
		if (selection instanceof IStructuredSelection) {
			IStructuredSelection ss = (IStructuredSelection)selection;
			Object element = ss.getFirstElement();
			if (element instanceof IJavaElement) {
				IJavaElement ele = (IJavaElement) ss.getFirstElement();
				RenameSaturnModuleProcessor renameSaturnModuleProcessor = new RenameSaturnModuleProcessor(ele);
				RenameRefactoring renamerefactoring = new RenameRefactoring(renameSaturnModuleProcessor);
				RenameSaturnModuleWizard renameSaturnModuleWizard = new RenameSaturnModuleWizard(renamerefactoring, 8);
				RefactoringWizardOpenOperation refactoringwizardopenoperation = new RefactoringWizardOpenOperation(renameSaturnModuleWizard);
				try {
					refactoringwizardopenoperation.run(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "rename");  //$NON-NLS-1$
				} catch (Exception _ex) {
				}
			}		
		}
	}

	public void selectionChanged(SelectionChangedEvent event) {
		this.selection = event.getSelection();
		setEnabled(computeEnabledState());
	}

	/*
	 * @see SelectionDispatchAction#update(ISelection)
	 */
	public void update(ISelection selection) {
		setEnabled(computeEnabledState());
	}

	private boolean computeEnabledState() {
		if (selection != null) {
			return true;
		} else {
			return false;
		}
	}

}
